package chen.view;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import javax.servlet.AsyncContext;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class JspRenderer extends Renderer {

    private String path;
    private Map<String, Object> model;
    private String type = "request";
    protected String contentType;

    public String getContentType() {
        return contentType;
    }

    public void setContentType(String contentType) {
        this.contentType = contentType;
    }
    public JspRenderer(String path) {
        this.path = path;
        this.model = new HashMap<String, Object>();
    }

    public JspRenderer(String path, Map<String, Object> model) {
        this.path = path;
        this.model = model;
    }

    public JspRenderer(String path, String modelKey, Object modelValue) {
        this.path = path;
        this.model = new HashMap<String, Object>();
        this.model.put(modelKey, modelValue);
    }
    
    public JspRenderer(String path, String modelKey, Object modelValue,String type) {
        this.path = path;
        this.model = new HashMap<String, Object>();
        this.model.put(modelKey, modelValue);
        this.type = type;
    }
    @Override
    public void render(ServletContext context, HttpServletRequest request, HttpServletResponse response,AsyncContext async) throws Exception {
        Set<String> keys = model.keySet();
        if(this.type.equals("request")){
            for (String key : keys) {
                request.setAttribute(key, model.get(key));
            }
        }else if(this.type.equals("session")){
            for (String key : keys) {
                request.getSession().setAttribute(key, model.get(key));
            }
        }else if(this.type.equals("application")){
            for (String key : keys) {
                request.getSession().getServletContext().setAttribute(key, model.get(key));
            }
        }

        request.getRequestDispatcher(path).forward(request, response);
    }
}